/**
 * 读、写文件流示例
 */

let fs = require("fs");

let data = "";

let readStream = fs.createReadStream("./input.txt");
let writeStream = fs.createWriteStream("./output.txt");

readStream.on("data", chunk => {
    console.log(chunk);

    data += chunk;

})

readStream.on("end", () => {
    console.log("end")
    writeStream.write(data, "utf8");
    writeStream.end(); //关闭流 类似于 Java 里的关闭流
})

readStream.on("error", (err) => {
    console.log("error", err);
})

writeStream.on("error", (err) => {
    console.log("error", err);
})


writeStream.on("finish", () => {
    console.log("finish");
    console.log(fs.lstatSync("./output.txt").isFile())
})

/**
 * 读写管道流示例
 */

let pipeReadStream = fs.createReadStream("./pipeInput.txt");
let pipeWriteStream = fs.createWriteStream("./pipeOut.txt");

pipeReadStream.pipe(pipeWriteStream);

/**
 * 链式流  TODO Node JS 文件夹打包和解压或者多个文件打包成一个文件？
 */

let zlib = require("zlib"); //打包工具库

//压缩
// fs.createReadStream("./zipInput.txt")
//     .pipe(zlib.createGunzip())
//     .pipe(fs.createWriteStream("zipInput.txt.gz"))
// console.log("压缩完成")
//
// //解压
// fs.createReadStream("./zipInput.txt.gz")
//     .pipe(zlib.createGunzip())
//     .pipe(fs.createWriteStream("./zipInput.un.txt"))
